﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data.Linq;
using System.Linq;
using System.Text;
using IntraVision.Web;
using IntraVision.Web.Filter;
using IntraVision.Web.Security;
using Model;


public enum LogOperationType : int
{
     OrderCreate = 1,  
     OrderChange,                        
     OrderStatusChange,
     OrderDelete,                 
     Login,                
     Logout,               
     UserCreate,              
     UserChange,             
     UserDelete,            
     ClientCreate,           
     ClientChange,          
     ClientDelete,         
     TaskCreate,        
     TaskChange,       
     TaskDelete,      
     KbCreate,     
     KbChange,    
     KbDelete,   
     KbDocumentCreate,  
     KbDocumentChange,
     KbDocumentDelete,
     OrderPaid                                                
}

[AllowedRole("finance", "logreport")]
public class LogReportController : TableController<NotarialServiceDataContext, Log>
{
    DateTime _StartDate;
    DateTime _EndDate;

    public LogReportController() 
    {
        _StartDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
        _EndDate = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(1).Month, 1).AddDays(-1);
    }

    public override void Default()
    {
        this.List();
    }

    public override void Create()
    {
        return;
    }

    public override void Delete()
    {
        return;
    }

    public override void Save()
    {
        return;
    }

    public override void List()
    {
        InitDatesFromRequest();

        ViewData["months"] = GetMonthList();
        ViewData["years"] = GetYearsList(DateTime.Now.Year, 10);
        ViewData["startdate"] = _StartDate;
        ViewData["enddate"] = _EndDate;

        base.List();
    }

    protected override IQueryable ConvertQueryToResult(NotarialServiceDataContext dc, IQueryable<Log> query)
    {
        return (from l in query
        select new
        {
            CreateDate = l.CreateDate,
            UserName = (l.UserId == null) ? "" : l.User.LastName + " " + l.User.Name + " " + l.User.PatronymicName,
            LogOperationName = l.LogOperation.Name,
            OrderId = l.OrderId.HasValue ? l.OrderId.ToString() : "",
            StatusName = l.StatusId.HasValue ? dc.Status.First(s => s.Id == l.StatusId).Name : ""
        });
    }

    protected override void CreateFilterConditions(NotarialServiceDataContext dc)
    {
        Filter = new Filter<Log>();
        Filter.Conditions.Add(new DateFilterCondition<Log>("CreateDate", "Дата/время операции"));
        Filter.Conditions.Add(new UserSelectFilterCondition<Log>("UserId", "Кто", (from u in dc.Users orderby u.LastName select new { Id = u.Id, Name = u.FullName }), -1, "task.ivp/findusers", "user.ivp/select?reset=true"));
        Filter.Conditions.Add(new SelectFilterCondition<Log>("LogOperationId", "Что", (from s in dc.LogOperations select new { Id = s.Id, Name = s.Name })));
        Filter.Conditions.Add(new NumericFilterCondition<Log>("OrderId", "Номер заявки", true));
        Filter.Conditions.Add(new SelectFilterCondition<Log>("StatusId", "Статус заявки", (from s in dc.Status select new { Id = s.Id, Name = s.Name })));                
    }

    protected override IQueryable<Log> CustomFilter(NotarialServiceDataContext dc, IQueryable<Log> query)
    {
        return query.Where(q => q.CreateDate >= _StartDate && q.CreateDate <= _EndDate);
    }

    private void InitDatesFromRequest()
    {
        DateTime bufDateTime;
        if (!String.IsNullOrEmpty(Request["startdate"]) && DateTime.TryParse(Request["startdate"], out bufDateTime))
        {
            _StartDate = bufDateTime;
            ViewData["currentYear"] = _StartDate.Year;
            ViewData["currentMonth"] = _StartDate.Month;
        }
        if (!String.IsNullOrEmpty(Request["enddate"]) && DateTime.TryParse(Request["enddate"], out bufDateTime))
            _EndDate = bufDateTime;
    }

    protected object GetMonthList()
    {
        int count = 12;
        List<object> monthsList = new List<object>(count);
        for (int i = 0; i < count; i++)
            monthsList.Add(new { id = i + 1, name = (DateTime.MinValue.AddMonths(i)).ToString("MMMM") });
        return monthsList;
    }

    protected object GetYearsList(int lastYear, int count)
    {
        List<object> yearList = new List<object>(count + 1);
        for (int i = lastYear; i >= lastYear - count; i--)
            yearList.Add(new { id = i, name = i.ToString() });
        return yearList;
    }

    public override void RegisterTableScripts()
    {
        base.RegisterTableScripts();

        RegisterScript("report/report.js");
    }
}


